package net.qqxh.common.utils;
import org.apache.any23.encoding.TikaEncodingDetector;
import org.apache.commons.io.IOUtils;
import org.apache.commons.io.filefilter.IOFileFilter;
import org.apache.commons.io.filefilter.SuffixFileFilter;
import org.apache.commons.io.filefilter.TrueFileFilter;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.util.ResourceUtils;
import org.springframework.util.StringUtils;

import java.io.*;
import java.net.URLEncoder;

/**
 * @author jason
 */
public class FileAnalysisTool {
    public static TikaEncodingDetector tikaEncodingDetector = new TikaEncodingDetector();

    public static String getFileFix(String fileName) {
        String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
        return suffix;
    }

    /**
     * 源文件和视图文件异地存储
     *
     * @param path
     * @param viewFix
     * @return
     */
    public static String getOffSiteViewDir(String srcDir, String viewDir, String path, String viewFix) {
        if (StringUtils.isEmpty(viewFix)) {
            return path;
        }
        File source = new File(srcDir);
        File view = new File(viewDir);
        String p = replaceFirst(path, source.getPath(), view.getPath());
        return p + "." + viewFix;
    }

    public static String getFileSourceByView(String srcDir, String viewDir, String path) {
        File source = new File(srcDir);
        File view = new File(viewDir);
        String p = replaceFirst(path, view.getPath(), source.getPath());
        return p.substring(0, p.lastIndexOf("."));
    }

    /**
     * 字符串替换，左边第一个。
     *
     * @param str    源字符串
     * @param oldStr 目标字符串
     * @param newStr 替换字符串
     * @return 替换后的字符串
     */
    public static String replaceFirst(String str, String oldStr, String newStr) {
        if (!newStr.endsWith(File.separator)) {
            newStr += File.separator;
        }
        if (!oldStr.endsWith(File.separator)) {
            oldStr += File.separator;
        }
        int i = str.indexOf(oldStr);
        if (i == -1) {
            return str;
        }
         str = str.substring(0, i) + newStr + str.substring(i + oldStr.length());

        return str;
    }

    /**
     * 将字符串中的中文进行编码
     *
     * @param s
     * @return 返回字符串中汉字编码后的字符串
     */
    public static String genIdByPath(String s) {
        char[] ch = s.toCharArray();
        String result = "";
        for (int i = 0; i < ch.length; i++) {
            char temp = ch[i];
            if (isChinese(temp)) {
                try {
                    String encode = URLEncoder.encode(String.valueOf(temp), "utf-8");
                    result = result + encode;
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
            } else {
                result = result + temp;
            }
        }
        return result;
    }

    /**
     * 判断字符是否为汉字
     *
     * @param c
     * @return
     */
    public static boolean isChinese(char c) {
        return c >= 0x4E00 && c <= 0x9FA5;
    }

    public static IOFileFilter getIOFileFilter(String[] supportExtensions) {
        IOFileFilter fileFilter;
        if (supportExtensions == null) {
            fileFilter = TrueFileFilter.INSTANCE;
        } else {
            String[] suffixes = toSuffixes(supportExtensions);
            fileFilter = new SuffixFileFilter(suffixes);
        }
        return fileFilter;
    }

    private static String[] toSuffixes(String[] extensions) {
        String[] suffixes = new String[extensions.length];

        for (int i = 0; i < extensions.length; ++i) {
            suffixes[i] = "." + extensions[i];
        }
        return suffixes;
    }

    public static String guessFileEncoding(File file) {
        return getCharsetDefault(file);
    }

    public static File getResFile(String filename) throws FileNotFoundException {
        File file = new File(filename);
        if (!file.exists()) {
            file = new File("config/" + filename);
        }
        Resource resource = new FileSystemResource(file);
        if (!resource.exists()) {
            file = ResourceUtils.getFile("classpath:" + filename);
        }
        return file;
    }

    public static String getCharsetDefault(File file){
        BufferedInputStream bin=null;
        FileInputStream fileInputStream=null;
        try {
            fileInputStream= new FileInputStream(file);
            bin = new BufferedInputStream(fileInputStream);
            String code= tikaEncodingDetector.guessEncoding(bin);
            new String(new byte[]{1,3,5,7},code);
            return tikaEncodingDetector.guessEncoding(bin);
        } catch (IOException e) {
            e.printStackTrace();
            return getCharset(file);
        }finally {
            IOUtils.closeQuietly(fileInputStream);
        }
    }


    /**
     * 获得文件编码
     *
     * @param file
     * @return
     * @throws Exception
     */
    public static String getCharset(File file) {
        String code = "GBK";
        BufferedInputStream bin=null;
        FileInputStream fileInputStream=null;
        try {
            fileInputStream= new FileInputStream(file);
            bin = new BufferedInputStream(fileInputStream);
            int p = (bin.read() << 8) + bin.read();
            bin.close();
            switch (p) {
                case 0xefbb:
                    code = "UTF-8";
                    break;
                case 0xfffe:
                    code = "Unicode";
                    break;
                case 0xfeff:
                    code = "UTF-16BE";
                    break;
                default:{

                }

            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            IOUtils.closeQuietly(bin);
            IOUtils.closeQuietly(fileInputStream);
        }
        return code;
    }



}
